<template>
    <div class="home">
        <div class="header">
            <div class="user" @click="clickUserName">
                <img src="@/assets/user.png" />
                <span>{{ monitorData.user }}</span>
            </div>
        </div>
        <FullCalendar :options="calendarOptions" />
        <div class="footer">
            <input type="file" ref="uploadFileInput" v-show="false" @change="readImportData" />
            <el-button type="success" @click="importData">导入</el-button>
            <el-button type="primary" @click="exportData">导出</el-button>
        </div>
    </div>
    <MeasureDialog
        ref="measureDialog"
        :measureHandlers="measureHandlers"
        v-model:glucose="glucoseValue"
        v-model:weight="weightValue"
    />
</template>

<script lang="ts" setup>
import FullCalendar, { CalendarOptions, EventClickArg, EventInput } from '@fullcalendar/vue3';
import dayGridPlugin from '@fullcalendar/daygrid';
import interactionPlugin, { DateClickArg } from '@fullcalendar/interaction';
import zhLocale from '@fullcalendar/core/locales/zh-cn';
import { ElMessageBox, ElButton } from 'element-plus';
import { useMonitor } from '@/utils/useMonitor';
import { Ref, ref, watchEffect } from 'vue';
import { getGlucoseBackgroundColor } from '@/utils/background';
import { useExport } from '@/utils/useExport';
import { useImport } from '@/utils/useImport';
import MeasureDialog from '@/components/Measure.vue';
import { MeasureType } from '@/utils/measureType';
import { MeasureDialogExpose } from '@/types';

const glucoseValue = ref(6);
const weightValue = ref(120);
const measureDialog: Ref<MeasureDialogExpose | null> = ref(null);

const { monitorData, add, modify, remove, modifyUser } = useMonitor(glucoseValue, weightValue);
const { exportData } = useExport(monitorData);

// 这里发现一个奇怪的问题，当把uploadFileInput的定义放到useImport里面的时候本地运行可以，但是发布后uploadFileInput并未绑到input上，只有将定义放到这个vue文件里才不出问题
const uploadFileInput: Ref<HTMLInputElement | null> = ref(null);
const { importData, readImportData } = useImport(monitorData, uploadFileInput);
const measureHandlers = {
    add,
    remove,
    modify
};

function getMeasureType(arg: EventClickArg) {
    if (arg.event.classNames.indexOf('glucose') !== -1) {
        return MeasureType.Glucose;
    }
    return MeasureType.Weight;
}

const calendarOptions = ref<CalendarOptions>({
    locale: zhLocale,
    plugins: [dayGridPlugin, interactionPlugin],
    initialView: 'dayGridMonth',
    fixedWeekCount: false,
    contentHeight: 480,
    eventBorderColor: 'white',
    headerToolbar: { start: 'title', center: '', end: 'prev next' },
    eventClick(arg: EventClickArg) {
        // 如果不加延时，有时会发生第一次加载对话框时会自己消失，看上去是此处eventClick内部采用了touchstart
        // 当点击的地方在对话框外面的时候就会有问题，增加延时显示后问题消失
        setTimeout(() => {
            measureDialog.value!.modify(getMeasureType(arg), arg.event.id, parseFloat(arg.event.title));
        }, 100);
    },
    dateClick(arg: DateClickArg) {
        setTimeout(() => {
            measureDialog.value!.add(arg.dateStr);
        }, 100);
    },
    events: []
});

watchEffect(() => {
    const glucoseArray = monitorData.value.glucose.map<EventInput>((data) => {
        return {
            id: data.id,
            title: data.value.toString(),
            allDay: true,
            start: data.date,
            backgroundColor: getGlucoseBackgroundColor(data.value),
            classNames: ['glucose']
        };
    });
    const weightArray = monitorData.value.weight.map<EventInput>((data) => {
        return {
            id: data.id,
            title: data.value.toString(),
            allDay: true,
            start: data.date,
            classNames: ['weight']
        };
    });
    calendarOptions.value.events = [...glucoseArray, ...weightArray];
});
const clickUserName = function () {
    ElMessageBox.prompt('', '请修改用户', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /.+/,
        inputValue: monitorData.value.user,
        inputErrorMessage: '用户名不能为空'
    })
        .then(({ value }) => {
            modifyUser(value);
        })
        .catch(() => {
            return 'ignore';
        });
};
</script>
<style lang="scss">
.home {
    margin: 0 5px;
    .header {
        text-align: right;
        padding: 10px 0;
        .user {
            display: inline;
            color: #666;
            img {
                vertical-align: middle;
                width: 28px;
                height: 28px;
            }
            span {
                vertical-align: middle;
                font-size: 22px;
                font-weight: bold;
                position: relative;
                top: 1px;
                margin-left: 3px;
            }
        }
    }
    .footer {
        margin-top: 15px;
        text-align: right;
    }
}
.fc .fc-button {
    padding: 0.2em;
}
.fc .fc-button-primary {
    background-color: #409eff;
    border-color: #409eff;
}

.fc .fc-button-primary:not(:disabled):hover,
.fc .fc-button-primary:not(:disabled).fc-button-active:hover,
.fc .fc-button-primary:not(:disabled):active:focus,
.fc .fc-button-primary:not(:disabled).fc-button-active:focus,
.fc .fc-button-primary:not(:disabled):active,
.fc .fc-button-primary:not(:disabled).fc-button-active {
    background-color: #0d84ff;
    border-color: #0d84ff;
    box-shadow: none;
}

.fc .fc-toolbar.fc-header-toolbar {
    margin-bottom: 1em;
}

.fc .fc-event.weight::before {
    position: absolute;
    content: '';
    width: 14px;
    height: 100%;
    top: -1px;
    left: 1px;
    background-image: url('../assets/body.png');
    background-size: 14px 14px;
    background-repeat: no-repeat;
    background-position: center center;
}
.fc .fc-event.glucose::before {
    position: absolute;
    content: '';
    width: 12px;
    height: 100%;
    left: 2px;
    background-image: url('../assets/blood.png');
    background-size: 12px 12px;
    background-repeat: no-repeat;
    background-position: center center;
}
.fc .fc-event-title {
    margin-left: 14px;
}
.fc-direction-ltr .fc-daygrid-event.fc-event-end,
.fc-direction-rtl .fc-daygrid-event.fc-event-start {
    margin-right: 0;
}
.fc-direction-ltr .fc-daygrid-event.fc-event-start,
.fc-direction-rtl .fc-daygrid-event.fc-event-end {
    margin-left: 0;
}
.el-message-box {
    width: 300px !important;
}
.el-dialog {
    max-width: 500px;
}
</style>
